<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>用户列表</span>
          <el-button type="primary" @click="handleAdd">添加用户</el-button>
        </div>
      </template>

      <el-table :data="userList" style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="age" label="年龄" width="80" />
        <el-table-column label="角色" width="200">
          <template #default="{ row }">
            <el-tag v-for="role in row.roles" :key="role.id">
              {{ role.name }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 用户表单对话框 -->
    <el-dialog
      :title="dialogType === 'create' ? '添加用户' : '编辑用户'"
      v-model="dialogVisible"
      width="500px"
    >{{ userForm }}
      <el-form
        ref="userForm"
        :model="userForm.value"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" />
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input-number v-model="userForm.age" :min="1" :max="120" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="dialogType === 'create'">
          <el-input v-model="userForm.password" type="password" />
        </el-form-item>
        <el-form-item label="角色" prop="roleIds">
          <el-select v-model="userForm.roleIds" multiple>
            <el-option
              v-for="role in roleList"
              :key="role.id"
              :label="role.name"
              :value="role.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { getUsers, createUser, updateUser, deleteUser } from '@/api/user'
import { getRoles } from '@/api/role'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'UserManagement',
  setup() {
    const userList = ref([])
    const roleList = ref([])
    const dialogVisible = ref(false)
    const dialogType = ref('create')
    const userForm = ref({
      id: null,
      username: '',
      email: '',
      age: null,
      password: '',
      roleIds: []
    })

    const rules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' }
      ],
      age: [
        { required: true, message: '请输入年龄', trigger: 'blur' }
      ]
    }

    const fetchUsers = async () => {
      try {
        const data = await getUsers()
        userList.value = data
      } catch (error) {
        console.error('获取用户列表失败:', error)
      }
    }

    const fetchRoles = async () => {
      try {
        const data = await getRoles()
        roleList.value = data
      } catch (error) {
        console.error('获取角色列表失败:', error)
      }
    }

    const handleAdd = () => {
      dialogType.value = 'create'
      dialogVisible.value = true
      userForm.value = {
        id: null,
        username: '',
        email: '',
        age: null,
        password: '',
        roleIds: []
      }
    }

    const handleEdit = (row) => {
      console.log(row)
      dialogType.value = 'update'
      dialogVisible.value = true
      userForm.value = {
        ...row,
        roleIds: row.roles.map(role => role.id)
      }
    }

    const handleDelete = async (row) => {
      try {
        await ElMessageBox.confirm('确认删除该用户吗？', '提示', {
          type: 'warning'
        })
        await deleteUser(row.id)
        ElMessage.success('删除成功')
        fetchUsers()
      } catch (error) {
        console.error('删除用户失败:', error)
      }
    }

    const submitForm = async () => {
      try {
        if (dialogType.value === 'create') {
          await createUser(userForm.value)
        } else {
          await updateUser(userForm.value.id, userForm.value)
        }
        ElMessage.success(dialogType.value === 'create' ? '添加成功' : '更新成功')
        dialogVisible.value = false
        fetchUsers()
      } catch (error) {
        console.error('操作失败:', error)
      }
    }

    onMounted(() => {
      fetchUsers()
      fetchRoles()
    })

    return {
      userList,
      roleList,
      dialogVisible,
      dialogType,
      userForm,
      rules,
      handleAdd,
      handleEdit,
      handleDelete,
      submitForm
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.el-tag {
  margin-right: 5px;
}
</style> 